import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Scanner;
import java.util.regex.Pattern;
import org.jgrapht.graph.*;



public class PPIFactory {
	static SimpleWeightedGraph<String, DefaultWeightedEdge> generate(HashMap<String, Gene> outGeneMap, 
			String filename) {
		if (outGeneMap == null) {
			System.err.println("PARFAIT error: PPI.Factory.generate() received null outGeneMap parameter.");
			return null;
		}
		
		SimpleWeightedGraph<String, DefaultWeightedEdge> net = 
			new SimpleWeightedGraph<String, DefaultWeightedEdge>(DefaultWeightedEdge.class);
			//new SimpleWeightedGraph<String, DefaultWeightedEdge>(DefaultWeightedEdge.class);
		
		String fullNetFileName = Consts.DATA_DIR + filename;

		// Read Network from file.
		BufferedReader netFile = null;
		String line;
		String prot1 = null,prot2 = null;
		double confidence = 0;
		String conf = null;

		try {
			netFile = new BufferedReader(new FileReader(fullNetFileName));
		} catch (IOException ioe) {
			System.err.println("PARFAIT: Error - can't open file "+filename+" for reading");
			System.exit(1);
		}
		try {
			while( ( (line = netFile.readLine()) != null )) {
				Scanner lineScan = new Scanner(line).useDelimiter(Pattern.compile("[ \t\n\f\r]"));
				if (lineScan.hasNext()) {
					prot1 = lineScan.next();
				}
				if (lineScan.hasNext()) {
					conf = lineScan.next();
				}
				if (lineScan.hasNext()) {
					prot2 = lineScan.next();
				}
				if ((prot1 != null) && (prot2 != null)) {
					conf = conf.substring(1,conf.length()-1); //Remove ( and ) from the confidence.
					//System.out.println(prot1+"\t"+prot2+"\t"+conf);
					confidence = Double.valueOf(conf); // Convert to double.
					
					// Add edge and possible nodes to the network.
					net.addVertex(prot1);
					net.addVertex(prot2);					
					DefaultWeightedEdge e = net.addEdge(prot1, prot2);
					net.setEdgeWeight(e, confidence);

					lineScan.close();
					prot1 = null;
					prot2 = null;
				}
			}
			netFile.close();
		} catch (IOException ieo) {
			System.err.println("having trouble reading file "+ netFile.toString());
			System.exit(1);
		}

		for (String s: net.vertexSet()) {
			outGeneMap.put(s, new Gene(s));
		}
		
		return net;
	}
}
